from django.db import models
from django.utils import timezone
import logging


# Create your models here.
# 消息表
class Message(models.Model):
    uid = models.CharField(max_length=20, verbose_name="用户名")
    msg = models.CharField(max_length=1024, verbose_name="消息")
    time = models.DateTimeField(default=timezone.now, verbose_name="时间")
    gid = models.CharField(max_length=20, verbose_name="房间号")


# 用户表
class User(models.Model):
    uid = models.CharField(max_length=20, verbose_name="用户名")
    pwd = models.CharField(max_length=255, verbose_name="密码")
    this_time = models.DateTimeField(verbose_name="本次登录时间")
    last_time = models.DateTimeField(verbose_name="上次登录时间")


# websocket连接表-----进入/创建房间才会创建websocket连接
class Websocket(models.Model):
    key = models.CharField(max_length=80, verbose_name="websocket连接")
    uid = models.CharField(max_length=20, verbose_name="用户名")
    gid = models.CharField(max_length=20, verbose_name="房间号")
    join_time = models.DateTimeField(default=timezone.now, verbose_name="加入时间")
    member_count = models.IntegerField(default=0, verbose_name="房间成员数量")

    @classmethod
    def update_member_count(cls, gid):
        member_count = cls.objects.filter(gid=gid).count()
        # 更新房间成员数量
        cls.objects.filter(gid=gid).update(member_count=member_count)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        # 加入房间后更新房间成员数量
        self.update_member_count(self.gid)

    def delete(self, *args, **kwargs):
        gid = self.gid
        super().delete(*args, **kwargs)
        # 离开房间后更新房间成员数量
        self.update_member_count(gid)
